<script setup>
import { apiIndex } from '../api/index'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Icon, Image as VanImage } from 'vant'

const myAudio = ref(null)
const audioUrl = ref('')
onMounted(async () => {
  
})

const route = useRoute()
const router = useRouter()
// 菜单列表
const sidebarList = ref([
  {
    id: 0,
    title: '全部',
    icon: 'icon-block-categories'
  }
])
const popupShow = ref(false)
const mapContainer = ref(null)
const mapInstance = ref(null)
// 初始化地图函数  
const initMap = () => {
  mapInstance.value = new BMap.Map(mapContainer.value)
  mapInstance.value.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
}

// 获取路由信息

if (route.params.villageId) {
  apiIndex({ villageId:route.params.villageId }).then(res => {
    console.log(res)
    const { lng, lat } = { ...res.data.village }
    // console.log('dfddddd', lng, lat)
    const point = new BMap.Point(lng, lat) // 设置地图中心点坐标
    mapInstance.value.centerAndZoom(point, 15) // 初始化地图，设置中心点和缩放级别
    const menu = res.data.menu.map(item => {
      return {
        id: item.id,
        title: item.title,
        icon: item.icon.name,
        marker: item.marker
      }
    })
    sidebarList.value.push(...menu)
  })
}

const selected = ref(-1)
const selectedMarker = ref(null)
// 选中菜单栏
const onSelected = (index) => {
  // console.log(sidebarList.value[index])
  selected.value = index
  mapInstance.value.clearOverlays()
  const bounds = new BMap.Bounds()
  const list = []
  if (sidebarList.value[index].id === 0) {
    // 全部
    console.log('ddd')
    sidebarList.value.forEach(itemMenu => {
      if (itemMenu.marker) {
        itemMenu.marker.forEach(itemMarker => {
          list.push(itemMarker)
        })
      }
    })
  } else {
    sidebarList.value[index].marker.forEach(itemMarker => {
      list.push(itemMarker)
    })
  }
  list.forEach(item => {
    const point = new BMap.Point(item.lng, item.lat)
    bounds.extend(point)
    const icon = new BMap.Icon(`https://sjdl1.hacaiwang.com/static/img/${sidebarList.value[index].icon}.png`, new BMap.Size(32, 32))
    const marker = new BMap.Marker(point, { icon })

    const label = new BMap.Label(item.title, {offset: new BMap.Size(16, 32)})
    label.setStyle({  
      transform: 'translateX(-50%)', // 水平居中 如果需要垂直居中，可以添加 translateY 的值，例如：'translate(-50%, -50%)'  
      border: 'none',
      color: '#fff',
      backgroundColor: '#000000aa',
      borderRadius: '4px',
      fontSize: '12px',
      padding: '1px 10px'

    });
    marker.setLabel(label) // 将文本覆盖物与标注关联

    // marker 点击标记事件
    const onHandel = (e) => {
      popupShow.value = true
      console.log(item)
      // console.log('sidebarList.value[index]', sidebarList.value[index].icon)
      selectedMarker.value = item
      // if (selectedMarker.value.voice) {
      if (item.voice) {
        // audioUrl.value = selectedMarker.value.voice.url
        audioUrl.value = item.voice.url
        // console.log('audioUrl.value', audioUrl.value)
        myAudio.value.addEventListener('ended', function() {
          popupAudioShow.value = false
        })
        // console.log('audioUrl.value', audioUrl.value)
      }
      
      // console.log('selectedMarker', selectedMarker.value)
    }
    // 添加事件
    label.addEventListener('click', onHandel)
    marker.addEventListener('click', onHandel)

    mapInstance.value.addOverlay(marker)
  })
  mapInstance.value.setViewport(bounds)
}

// 定位当前位置
const onLocation = () => {
  console.log('dfd')
  // const map = new BMap.Map("allmap");
  mapInstance.value
  // const point = new BMap.Point(116.331398,39.897445);
  // map.centerAndZoom(point,12);

  const geolocation = new BMap.Geolocation();
  geolocation.getCurrentPosition(function(r){
    if(this.getStatus() == BMAP_STATUS_SUCCESS){

      const icon = new BMap.Icon('https://sjdl1.hacaiwang.com/static/img/dangqian.png', new BMap.Size(32, 32))
      const mk = new BMap.Marker(r.point, { icon })
      mapInstance.value.addOverlay(mk)
      mapInstance.value.panTo(r.point)
      // alert('您的位置：'+r.point.lng+','+r.point.lat);
    }
    else {
      alert('failed'+this.getStatus());
    }
  })
}

// 到这区 唤起地图
const onJumpNav = () => {
  console.log('dd', selectedMarker.value)
  // http://api.map.baidu.com/marker?location=40.047669,116.313082&title=我的位置&content=百度奎科大厦&output=html&src=webapp.baidu.openAPIdemo
//调起百度PC或web地图，且在（lat:39.916979519873，lng:116.41004950566）坐标点上显示名称"我的位置"，内容"百度奎科大厦"的信息窗口。 
  window.open(`http://api.map.baidu.com/marker?location=${selectedMarker.value.lat},${selectedMarker.value.lng}&title=${selectedMarker.value.title}&content=${selectedMarker.value.details}&output=html&src=webapp.baidu.openAPIdemo`)
}

// 详情跳转
const onJumpDetails = () => {
  router.push({ path: '/details', query: { id: selectedMarker.value.id } })
}

// 讲解弹窗
const popupAudioShow = ref(false)
const onAudioPlay = async () => {
  
  // audioUrl.value = 'http://map.cx/storage/topic/20240503/42d691e0adaa0f89085b6b132fc1ae67.mp3'
  popupAudioShow.value = true
  console.log('audioUrl', audioUrl.value)
  await nextTick()
  myAudio.value.play()
}

const onAudioClose = () => {
  popupAudioShow.value = false
  myAudio.value.pause()
}

onMounted(() => {
  // console.log('ddddddddddd')
  initMap()
})
</script>

<template>
  <div class="container">

    <div class="sidebar">
      <div
        v-for="(item, index) in sidebarList"
        :key="item.id" 
        class="sidebar-item"
        @click="onSelected(index)"
        :class="{ active: selected === index }"
      >
        <div>
          <span :class="item.icon" class="base-icon iconfont"></span>
        </div>
        <div>{{ item.title }}</div>
      </div>
    </div>

    <div ref="mapContainer" class="map-wrap">
    </div>

    <div class="popup-container">
      <div class="location-wrap">
        <div @click="onLocation">
          <span class="iconfont icon-dingwei"></span>
        </div>
      </div>
      <div class="popup-main" v-show="popupShow">
        <div class="popup-close" @click="popupShow=false">
          <Icon name="clear"/>
        </div>
        <div class="popup-content">
          <div class="details-thumbnail">
            <VanImage fit="cover" class="img-thumbnail" :src="selectedMarker && selectedMarker.thumbnail.url" />
          </div>
          <div class="details-right">
            <div class="details-title">{{ selectedMarker && selectedMarker.title}}</div>
            <div class="details-description van-multi-ellipsis--l2">{{ selectedMarker && selectedMarker.details}}</div>
          </div>
        </div>
        <div class="popup-handle">
          <div @click="onJumpNav">
            <Icon name="guide-o" />
            <span>到这去</span>
          </div>
          <div class="popup-handle-btn" @click="onJumpDetails">
            <div>详情</div>
          </div>
          <div class="popup-handle-btn" @click="onAudioPlay" v-show="selectedMarker && selectedMarker.voice">
            <div>讲解</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 讲解弹窗 -->
    <div class="popup-audio" v-show="popupAudioShow">
      <div class="popup-audio-main">
        <div class="popup-audio-main-left">
          <div class="wave">
            <div style="animation-delay: .3s;"></div>
            <div style="animation-delay: .4s;"></div>
            <div style="animation-delay: .6s;"></div>
            <div style="animation-delay: .8s;"></div>
            <div style="animation-delay: 1s;"></div>
          </div>
          <div class="popup-audio-main-left-text">正在播放中：</div>
        </div>
        <div class="popup-audio-main-right" @click="onAudioClose">
          <Icon name="cross" />
        </div>
      </div>
    </div>

    <audio ref="myAudio" :src="audioUrl" controls style="display: none;">  
      <!-- <source :src="audioUrl" type="audio/mpeg">   -->
    </audio>
  </div>
</template>

<style scoped>
.container {
  position: relative;
  font-size: 28px;
}
.sidebar {
  position: fixed;
  top: 20px;
  left: 20px;
  width: 100px;
  /* height: 800px; */
  border-radius: 10px;
  text-align: center;
  overflow: hidden;
  z-index: 10;
  /* padding: 20px 0; */
  background-color: #fff;
  /* padding: 10px 0;
  box-sizing: border-box; */
}
.icon {
  font-size: 50px;
}
.sidebar-item {
  margin: 12px 0;
  /* background-color: #33D598;
  color: #fff; */
  font-size: 24px;
  font-weight: 400;
  color: #33D598;
  padding: 8px 0;
}
.map-wrap {
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  background-color: brown;
}
.base-icon {
  font-size: 50px;
}
.active {
  background-color: #33D598;
  color: #fff;
}
.t {
  border: none;
  color: #fff;
  background-color: #00000077;
  border-radius: 10px;
}
.popup-container {
  position: fixed;
  width: 100%;
  bottom: 20px;
  padding: 0 20px;
  box-sizing: border-box;
  overflow: hidden;
}
.location-wrap {
  /* background-color: #fff
   */
  margin: 0 0 80px 0;
  display: flex;
}
.location-wrap > div {
  background-color: #fff;
  padding: 20px;
  border-radius: 50%;
}
.popup-main {
  position: relative;
  background-color: #fff;
  border-radius: 20px;
}
.popup-close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 40px;
  color: #00000044;
}
.popup-content {
  display: flex;
  padding: 24px;
  border-bottom: 1px #eee solid;
}
.img-thumbnail {
  width: 180px;
  height: 180px;
  border-radius: 10px;
  overflow: hidden;
}
.details-right {
  margin: 0 0 0 20px;
}
.details-title {
  font-size: 32px;
  font-weight: 600;
}
.details-description {
  font-size: 24px;
  margin: 20px 0 0 0;
}
.popup-handle {
  display: flex;
  text-align: center;
  justify-content: space-between;
}
.popup-handle > div {
  flex: 1;
  /* width: 33.33%; */
  padding: 24px 0;
}
.popup-handle-btn > div{
  border-left: 1px #eee solid;
}
.popup-audio {
  position: fixed;
  top: 40px;
  width: 100%;
  z-index: 10;
  padding: 20px 40px;
  box-sizing: border-box;


}
.popup-audio-main {
  background-color: #00000099;
  height: 80px;
  border-radius: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  padding: 0 30px;
}
.popup-audio-main-left {
  display: flex;
}
.popup-audio-main-right {
  font-size: 36px;
}
.wave {
  display: flex;
  /* width: 60px; */
  /* justify-content: space-between; */
  align-items: center;
  /* margin: 0 0 0 20px; */
}
@keyframes colorChange {  
  0%   {height: 4px;}
  30% {height:12px}
  60% {height:18px}
  80% {height:12px}
  100% {height:4px}
}
.wave > div {
  width: 6px;
  height: 0px;
  background: #ffffff;
  border-radius: 10px;
  -webkit-animation: colorChange 1s infinite ease;
  animation: colorChange 1s infinite ease;
  margin: 0 6px 0 0;
}
.popup-audio-main-left-text {
  margin: 0 0 0 20px;
}
</style>